﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Net;
using System.Net.Sockets;
using Common;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using Server.DispatcherService;
using System.ServiceModel;
using System.Threading;

namespace Server
{
	class Program
	{
		static ServerTerminal _server;
		static DispatcherClient _dispatcher;

		static bool _stop;

		public static void Main()
		{
			IDispatcherCallbackImpl impl = new IDispatcherCallbackImpl();
			InstanceContext context = new InstanceContext(impl);
			_dispatcher = new DispatcherClient(context);
			_dispatcher.Open();
			Console.WriteLine("Connected");

			_server = new ServerTerminal();
			_server.MessageRecived += new Common.TCPTerminal_MessageRecivedDel(server_MessageRecived);
			_server.ClientConnect += new Common.TCPTerminal_ConnectDel(server_ClientConnect);
			_server.ClientDisconnect += new Common.TCPTerminal_DisconnectDel(server_ClientDisconnect);

			IPAddress[] addresses = Dns.GetHostAddresses(Dns.GetHostName());
			string address = addresses.Length != 0 ? addresses[addresses.Length - 1].ToString() : "localhost";
			_dispatcher.RegisterServer(addresses[addresses.Length - 1].ToString());
			Console.WriteLine("Created");
			_server.StartListen((int)Ports.ClientToServerPort);
			_stop = false;

			while (!_stop)
			{
			}

			_server.Close();
			_dispatcher.Close();
		}

		static void server_ClientDisconnect(System.Net.Sockets.Socket socket)
		{
			//throw new NotImplementedException();
		}

		static void server_ClientConnect(System.Net.Sockets.Socket socket)
		{
			//throw new NotImplementedException();
		}

		static void server_MessageRecived(System.Net.Sockets.Socket socket, byte[] buffer)
		{
			MemoryStream stream = new MemoryStream(buffer);
			BinaryFormatter formatter = new BinaryFormatter();
			ServerMessage msg = formatter.Deserialize(stream) as ServerMessage;
			switch (msg.Type)
			{
				case ServerMessageType.PlayerTurn: 
				case ServerMessageType.PlayerLost:
					_server.DistributeMessage(buffer);
					break;
			}
			//throw new NotImplementedException();
		}
	}
}
